import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus';
import { EmployeeStore, EmployeeInfoDetailModel } from '/@/interfaces/SystemserviceModel';
import { Session } from '/@/utils/storage';
import CONSTANTS from '/@/enums/global-constant-enum';
import useObjectUtil from '/@/utils/objectUtil';

export const useEmployeeStore = defineStore('employee', {
    state: (): EmployeeStore => ({
        token: '',
        loading: false,
        loadStartTime: 0,
        employee: {
            id: '',
            userId: '',
            employeeName: '',
            employeeTel: '',
            headUrl: '',
            employeeStatus: 0,
            email: '',
            sex: 0,
            orgList: [],
            roleList: [],
            funcIdList: [],
            createTime: new Date(),
            updateTime: new Date(),
        }
    }),
    actions: {
        setToken(token = '') {
            this.token = token;
            Session.set(CONSTANTS.Authorization, token);
        },
        setEmployeeInfo(data: EmployeeInfoDetailModel) {
            useObjectUtil.copyProperties(data, this.employee);
            this.employee.funcIdList = this.getFuncIds();
            Session.set(CONSTANTS.SESSION_EMPLOYEE_INFO, JSON.stringify(this.employee));
        },
        getHasLogin() {
            if (useObjectUtil.isNull(this.token) && useObjectUtil.isNull(Session.get(CONSTANTS.Authorization))) {
                return false;
            }
            return true;
        },
        getEmployeeInfo() {
            if(useObjectUtil.isNotNull(this.employee) && useObjectUtil.isNotNull(this.employee.id)) {
                return this.employee;
            }
            const cacheSession: EmployeeInfoDetailModel = JSON.parse(Session.get(CONSTANTS.SESSION_EMPLOYEE_INFO) as string);
            if(!cacheSession || useObjectUtil.isNull(cacheSession.id)) {
                ElMessage.error("你已被登出，请重新登录");
            }
            this.employee = {...cacheSession};
            return cacheSession;
        },
        getToken(): string | null {
            if(useObjectUtil.isNull(this.token)) {
                this.token = Session.get(CONSTANTS.Authorization);
            }
            return this.token;
        },
        getFuncIds(): string[] {
            return ['jdfHome','jdfRegister','jdfConfig','jdfFile','jdfLog','jdfPlatform','jdfUser',];
        },
    }
});